var jstree = $.tree_create();
$(function() {
	jstree.init($('#tree'), {
		data: {
			type: 'json',
			async: true,
			url: 'tree-node/'
		},
		cookies: {},
		ui: {
			dots: false,
			animation: 250,
			context: false
		},
		rules: {
			deletable: ['page'],
			draggable: ['page'],
			dragrules: [
				'page inside root',
				'page inside page',
				'page before page',
				'page after page'
			]
		},
		lang: {
			new_node: 'Untitled page',
			loading: ' '
		},
		callback: {
			onrgtclk: function(node, tree_obj, e) {
				e.preventDefault();
			},
			onmove: function(node, ref_node, type, tree_obj) {
				$.post('actions/move/', { id: $(node).attr('id'), ref_id: $(ref_node).attr('id'), type: type }, function(responseJson) {
				}, 'json');
			},
			beforechange: function(node, tree_obj) {
				//$('.richtext').each(function() { tinyMCE.execCommand('mceRemoveControl', false, $(this).attr('id')); });
			}, 
			onchange: function(node, tree_obj) {
				$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
				$('.blockMsg').hide();
				$.get('?id='+node.id, function() {
					if ($(node).attr('rel')=='root') {
						$('a.delete').addClass('disabled');
					} else {
						$('a.delete').removeClass('disabled');
					}
					$('a.save').addClass('disabled');
					$.unblockUI();
					//initTinyMce();
				});
			},
			ondelete: function(node, tree_obj) {
				$.post('actions/delete/', { id: $(node).attr('id') }, function(responseJson) {
				}, 'json');
			},
			onload: function(tree_obj) {
				$('#tree').find('.no-children').removeClass('open').removeClass('closed');
				if (!$('#tree a.clicked').length) {
					$('#tree a:first').click();
				}
			},
			onopen: function(node, tree_obj) {
				$(node).find('.no-children').removeClass('open').removeClass('closed').removeClass('no-children');
			}
		}
	});
	
	function jstree_create() {
		$.post('actions/create/', { parent_id: jstree.selected.attr('id') }, function(responseJson) {
			var already_opened = jstree.selected.find('li').length;
			jstree.selected.removeClass('leaf'); // open_branch fails when it has class "leaf" - I guess cos it assumes there's nothing beneath it to open.
			jstree.open_branch(jstree.selected, false, function() {
				if (already_opened) {
					// children loaded
					var new_li = jstree.create({
						"attributes": {
							"id": responseJson.id,
							"class": "inactive",
							"rel": "page",
							"parent_id": jstree.selected.attr('id')
						},
						"state": "closed",
						"data": {
							"title":"Untitled page",
							"icon":"/admin/backend/resources/images/icons/folder.png"
						}
					});
					jstree.select_branch(new_li);
					new_li.removeClass('open').removeClass('closed');
				} else {
					// never been opened
					jstree.select_branch(jstree.get_node(jstree.selected.find('li:last-child')));
				}
				//
			});
			$("ul.tabs").tabs('select', 0);
		}, 'json');
	}
	
	$('a.create').click(function(e) {
		e.preventDefault();
		jstree_create();
	});
	$('a.delete').click(function(e) {
		e.preventDefault();
		if (confirm('Are you sure you want to remove this page?')) {
			jstree.remove();
		}
	});
	
	
	$("div.tabs").bind('tabsselect', function(e, ui) {
		if ($(ui.tab).attr('href') == '#preview' && pageHasChanged) {
			$('a.save').click();
		}
	});
	$('ul.tabs a[href="#preview"]').click(function(e) {
		$('#preview iframe').attr('src', $('#preview iframe').attr('src'));
		resize();
	});
	
	/*
	 * Link header save button to form.
	 *
	 */
	$('a.save:not(.disabled)').livequery('click', function() {
		jstree.selected.addClass('unpublished');
	});
	$('a.publish:not(.disabled)').livequery('click', function(e) {
		e.preventDefault();
		$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
		$('.blockMsg').hide();
		$.post('actions/publish/', { id: $('#id').val() }, function(responseJson) {
			$('a.publish').addClass('disabled');
			$('a.revert').addClass('disabled');
			$('a.resume').parent().addClass('hidden');
			$('a.suspend').parent().removeClass('hidden');
			jstree.selected.removeClass('unpublished').removeClass('inactive');
			if ($('#context').val() == 'navigation') {
				jstree.selected.removeClass('none');
				jstree.selected.find('> a').css('background-image', 'url(/admin/backend/resources/images/icons/folder.png)');
			} else if ($('#context').val() == 'none') {
				jstree.selected.removeClass('navigation');
				jstree.selected.find('> a').css('background-image', 'url(/admin/backend/resources/images/icons/page_white.png)');
			}
			$.unblockUI();
		}, 'json');
	});
	$('a.revert:not(.disabled)').livequery('click', function(e) {
		e.preventDefault();
		$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
		$('.blockMsg').hide();
		$.post('actions/revert/', { id: $('#id').val() }, function(responseJson) {
			$.get('?id=' + responseJson.id);
			jstree.selected.removeClass('unpublished');
			$.unblockUI();
		}, 'json');
	});
	$('a.suspend').livequery('click', function(e) {
		e.preventDefault();
		$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
		$('.blockMsg').hide();
		$.post('actions/suspend/', { id: $('#id').val() }, function(responseJson) {
			$('a.suspend').parent().addClass('hidden');
			$('a.resume').parent().removeClass('hidden');
			jstree.selected.addClass('inactive');
			$.unblockUI();
		}, 'json');
	});
	$('a.resume').livequery('click', function(e) {
		e.preventDefault();
		$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
		$('.blockMsg').hide();
		$.post('actions/resume/', { id: $('#id').val() }, function(responseJson) {
			if (responseJson.ok==true) {
				$('a.resume').parent().addClass('hidden');
				$('a.suspend').parent().removeClass('hidden');
				jstree.selected.removeClass('inactive');
				$.unblockUI();
			} else {
				
			}
		}, 'json');
	});
	
	/*
	 * Plugins
	 *
	 */
	$('table.plugins textarea').attr('wrap', 'off').livequery('focus', function() {
		$(this).animate({ height: 250 }, 250);
	}).livequery('blur', function() {
		$(this).animate({ height: 50 }, 250);
	});
	$('table.plugins input[type=checkbox]').livequery('change', function() {
		if ($(this).is(':checked')) {
			$('#' + $(this).closest('tr').attr('id') + '_config').show();
		} else {
			$('#' + $(this).closest('tr').attr('id') + '_config').hide();
		}
	});
	
	/*
	 * Breadcrumb
	 *
	 */
	$('.breadcrumb a').livequery('click', function(e) {
		e.preventDefault();
		$.tree_reference('tree').select_branch($($(this).attr('href')));
	});
	
	/*
	 * Manage path checkboxes
	 *
	 */
	$('input.manage-path').livequery('click', function() {
		if ($(this).is(':checked')) {
			$('input.manage-path').attr('checked', false);
			$(this).attr('checked', true);
		}
	});
	
	/*
	 * Image preview
	 *
	 */
	$('select.image').livequery('change', function() {
		$(this).closest('div').find('.image-preview').html($(this).val() ? '<img src="/images/' + ($(this).attr('rel') ? $(this).attr('rel')+'/' : '') + $(this).val() + '/imagefilename" />' : '');
	});
	
	/*
	 * Contexts
	 *
	 */
	$('#context').livequery('change', function() {
		if ($(this).val() == '_other_') {
			$('#context_other').show().focus();
		} else {
			$('#context_other').hide();
		}
	});
	
});